//
//  CalendarPageView.m
//  FindJob
//
//  Created by apple on 16/3/9.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CalendarPageView.h"

static NSString *const kCalendarCellId = @"cellid";
@interface CalendarCell : UICollectionViewCell
@property (nonatomic, strong) UILabel *dayLabel;
@property (nonatomic, strong) UILabel *chineseLabel;


@end

@implementation CalendarCell

- (UILabel *)dayLabel{
    if (!_dayLabel) {
        _dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 20)];
        _dayLabel.textColor = [UIColor whiteColor];
        _dayLabel.textAlignment = NSTextAlignmentCenter;
        _dayLabel.font = [UIFont systemFontOfSize:14];
        [self addSubview:_dayLabel];
    }
    return _dayLabel;
}
- (UILabel *)chineseLabel{
    if (!_chineseLabel) {
        _chineseLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 20, self.frame.size.width, 20)];
        _chineseLabel.textAlignment = NSTextAlignmentCenter;
        _chineseLabel.font = [UIFont systemFontOfSize:12];
        _chineseLabel.textColor = [UIColor orangeColor];
        [self addSubview:_chineseLabel];
    }
    return _chineseLabel;
}

@end

@interface CalendarPageView ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@end
@implementation CalendarPageView
- (instancetype)initWithFrame:(CGRect)frame date:(NSDate *)date{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.collectionView.backgroundColor = [UIColor clearColor];
        self.curretDisplayDate = date;
        self.selectedDate = date;
        [self addSubview:self.collectionView];
    }
    return self;
}
#pragma mark - public

// 获取上一个月的date
- (NSDate *)dateOfLastMonth{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = -1;
    NSDate *date = [calendar dateByAddingComponents:components toDate:self.curretDisplayDate options:NSCalendarSearchBackwards];
    return date;
}
// 获取当前月的下一个月的date
- (NSDate *)dateOfNextMonth{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    NSDate *date = [calendar dateByAddingComponents:components toDate:self.curretDisplayDate options:NSCalendarMatchStrictly];
    return date;
}

#pragma mark - private
// 获取当前这月的第一天是星期几
- (NSInteger )weekdayOfFirstDayCurrentMonth{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekday fromDate:self.curretDisplayDate];
    components.day = 1;
    NSDate *fistDate = [calendar dateFromComponents:components];
    NSInteger weekday = [calendar component:NSCalendarUnitWeekday fromDate:fistDate];
    return weekday;
}
- (NSInteger)totalDayofMonthInDate:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 获取date的日历组成部分在大的日历组成部分的范围
  NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return range.length;
}


// 日期转换成农历
- (NSString *)chineseDateFromDate:(NSDate *)date{
    // 获取到中国的日历
    NSCalendar *chinesCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    NSDateComponents *components = [chinesCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    NSString *dayStr;
    if (components.day == 1) {
        dayStr = self.chineseMoths[components.month - 1];
    }else{
        dayStr = self.chineseDays[components.day - 1];
    }
    return dayStr;
}
// 第一个参数是你要现实的日期 同过该日期或年
// 获取
- (NSDate *)dateFromDate:(NSDate *)date day:(NSInteger )day{
    // 获取当前显示的date 的年月
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:self.curretDisplayDate];
    // 给日赋值
    components.day = day;
    // 把日期的组件转换成NSdate
    NSDate *upDate = [[NSCalendar currentCalendar] dateFromComponents:components];
    return upDate;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 42;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCalendarCellId forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.dayLabel.textColor = [UIColor whiteColor];
    
    
    NSInteger weekFistDay = [self weekdayOfFirstDayCurrentMonth];
    NSInteger totalDaysInCurrentMonth = [self totalDayofMonthInDate:self.curretDisplayDate];
    NSInteger totalDaysInLastMonth = [self totalDayofMonthInDate:[self dateOfLastMonth]];
    if (indexPath.item < weekFistDay - 1) {
        NSInteger day = totalDaysInLastMonth - (weekFistDay - 1) + indexPath.item + 1;
        NSString *dayStr = [NSString stringWithFormat:@"%ld",day];
        cell.dayLabel.text = dayStr;
        cell.dayLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        // 获取当前cell 表示的日期
        NSDate *date = [self dateFromDate:[self dateOfLastMonth] day:day];
        NSString *chineseDay = [self chineseDateFromDate:date];
        cell.chineseLabel.text = chineseDay;
        
    }else if(indexPath.item > weekFistDay - 1 + totalDaysInCurrentMonth - 1){
        NSInteger day = indexPath.item - (weekFistDay - 1 + totalDaysInCurrentMonth - 1);
        NSString *dayStr = [NSString stringWithFormat:@"%ld",day];
        cell.dayLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        cell.dayLabel.text = dayStr;
        NSDate *date = [self dateFromDate:[self dateOfNextMonth] day:day];
        NSString *chineseDay = [self chineseDateFromDate:date];
        cell.chineseLabel.text = chineseDay;
    }else{
        NSInteger day = indexPath.item - (weekFistDay - 1) + 1;
        NSString *dayStr = [NSString stringWithFormat:@"%ld",day];
        cell.dayLabel.text = dayStr;
        // 将公历转换为农历
        NSDate *date = [self dateFromDate:self.curretDisplayDate day:day];
        NSString *chineseDay = [self chineseDateFromDate:date];
        cell.chineseLabel.text = chineseDay;
        
        // 如果当前选中的日期，高亮显示
//        if ([date isEqualToDate:self.selectedDate]) {
//            cell.backgroundColor = [UIColor whiteColor];
//            cell.dayLabel.textColor = [UIColor colorWithRed:25.0/255 green:208/255 blue:208/255 alpha:1];
//            cell.layer.cornerRadius = cell.frame.size.width / 2;
//        }
//        if ([date isEqualToDate:[NSDate date]]) {
//            cell.backgroundColor = [UIColor whiteColor];
//            cell.dayLabel.textColor = [UIColor colorWithRed:25.0/255 green:208/255 blue:208/255 alpha:1];
//            cell.layer.cornerRadius = cell.frame.size.width / 2;
//        }
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        if ([calendar isDate:date equalToDate:[NSDate date]  toUnitGranularity:NSCalendarUnitYear] && [calendar isDate:date equalToDate:[NSDate date] toUnitGranularity:NSCalendarUnitMonth] && [calendar isDate:date equalToDate:[NSDate date] toUnitGranularity:NSCalendarUnitDay]) {
            cell.backgroundColor = [UIColor whiteColor];
            cell.dayLabel.textColor = [UIColor redColor];
            cell.layer.cornerRadius = cell.frame.size.width / 2;
        }
        
    }
    return cell;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger weekOfFirstDay = [self weekdayOfFirstDayCurrentMonth];
    NSInteger totalDayInCurrentMonth = [self totalDayofMonthInDate:self.curretDisplayDate];
  
    // weekOfFirstDay - 1
    if (indexPath.item < weekOfFirstDay - 1) {
        // 上个月
    }else if (indexPath.item > weekOfFirstDay - 1 + totalDayInCurrentMonth - 1){
        //weekOfFirstDay - 1 + totalDayInCurrentMonth - 1 当前月最后一天的下标
        // 下个月
    }else{
        // 获取当前选中的日期
        NSInteger day = indexPath.item - (weekOfFirstDay - 1) + 1;
        NSDate *date = [self dateFromDate:self.curretDisplayDate day:day];
        self.selectedDate = date;
        
        NSTimeZone *timezone = [NSTimeZone systemTimeZone];
        NSTimeInterval  interval = [timezone secondsFromGMTForDate:date];
        NSDate *resultDate = [date dateByAddingTimeInterval:interval];
        NSLog(@"select date = %@",resultDate);
        
        [self.collectionView reloadData];
        if ([self.delegate respondsToSelector:@selector(calendarPageView:didSelectedDate:)]) {
            [self.delegate calendarPageView:self didSelectedDate:resultDate];
        }
    }
    
}
#pragma mark - setters
- (void)setCurretDisplayDate:(NSDate *)curretDisplayDate{
    _curretDisplayDate = curretDisplayDate;
    [self.collectionView reloadData];
}


#pragma mark - getters
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        CGFloat itemWidth = self.frame.size.width / 7;
        
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, itemWidth * 6) collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[CalendarCell class] forCellWithReuseIdentifier:kCalendarCellId];
        
     }
    return _collectionView;
}
- (NSArray *)chineseDays{
    if (!_chineseDays) {
        _chineseDays = @[@"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",@"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十", @"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十"];
    }
    return _chineseDays;
}
- (NSArray *)chineseMoths{
    if (!_chineseMoths) {
        _chineseMoths = @[@"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",@"九月", @"十月", @"冬月", @"腊月"];
    }
    return _chineseMoths;
}
@end
